﻿//        Another Demo from Andy L. & MissedMemo.com
// Borrow whatever code seems useful - just don't try to hold
// me responsible for any ill effects. My demos sometimes use
// licensed images which CANNOT legally be copied and reused.

using System;
using System.Windows;
using System.Linq;
using System.ServiceModel;

using MissedMemo.MeatAndCheeseDisc.OrderEntry.OrderProcessing;


namespace MissedMemo.MeatAndCheeseDisc.OrderEntry
{
    //[CallbackBehavior(UseSynchronizationContext=false)] ( not needed IF ALL COMMUNICATION IS 'OneWay' )
    public class OrderEntryServiceAbstraction : IOrderEntryManagementServiceCallback
    {

    #region PizzaFinishedEventArgs...

        public class PizzaFinishedEventArgs : EventArgs
        {
            public int NowServingNumber { get; private set; }
            public Pizza FinishedPizza { get; private set; }

            public PizzaFinishedEventArgs( int nowServingNumber, Pizza finishedPizza )
            {
                NowServingNumber = nowServingNumber;
                FinishedPizza = finishedPizza;
            }
        }

    #endregion (PizzaFinishedEventArgs)


        private OrderEntryManagementServiceClient _proxy = null;

        public event EventHandler<PizzaFinishedEventArgs> NotifyPizzaIsDone;


        public OrderEntryServiceAbstraction()
        {
            _proxy = new OrderEntryManagementServiceClient( new InstanceContext( this ) );

            try
            {
                _proxy.SubscribeOrderEntryManagerNotifications();
            }
            catch( EndpointNotFoundException e )
            {
                string strMsg = string.Format( "Service host must be running before starting the client.", e );
                MessageBox.Show( strMsg, "Service not found" );
                
                App.Current.Shutdown();
            }
        }


        public void ProcessOrder( Order order )
        {
            _proxy.ProcessOrder( order );
        }


        public void DeleteOrder( int orderID )
        {
            _proxy.DeleteOrder( orderID );
        }

        
        // Relay notification of finished pizza to CLIENT WINDOW, to update UI

        public void OnNotificationPizzaIsDone( int nowServingNumber, Pizza finishedPizza )
        {
            if( NotifyPizzaIsDone != null )
            {
                NotifyPizzaIsDone( this, new PizzaFinishedEventArgs( nowServingNumber, finishedPizza ) );
            }
        }


        public void Close()
        {
            if( _proxy.State != CommunicationState.Faulted )
            {
                _proxy.UnsubscribeOrderEntryManagerNotifications();

                _proxy.Close();
                _proxy = null;
            }
        }
    }
}
